import 'package:app/component/common_components.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

/// v层基类
abstract class BaseView {
  BuildContext getContext();

  //显示加载loading
  void showLoading();

  //隐藏loading
  void hideLoading();

  //显示吐司
  void showToast(String msg);
  /***
   * 设置按钮索引-用于控制禁用启用的
   */
  void setCurrentBtnName(String btnName);
  String getCurrentBtnName();
  // 设置加载状态
  void setLoading(bool loading);
  bool getLoading();
}

/// p层抽象类
abstract class IPresenter {
  void deactivatePresenter();
  void disposePresenter();
  void initPresenter();
}

/// p层基类
class BasePresenter<V extends BaseView> extends IPresenter {
  V view;
  CancelToken _cancelToken;

  @override
  void deactivatePresenter() {}

  @override
  void disposePresenter() {
    //请求取消
    if (_cancelToken != null) {
      if (_cancelToken.isCancelled) {
        _cancelToken.cancel();
      }
    }
  }

  @override
  void initPresenter() {}
}

/// State 基类
abstract class BaseState<T extends StatefulWidget, V extends BasePresenter>
    extends State<T> implements BaseView {
  V presenter;
  String currentBtnName = "";
  bool loading = false;
  V createPresenter();
  BaseState() {
    presenter = createPresenter();
    presenter.view = this;
  }
  @override
  BuildContext getContext() {
    return context;
  }

  bool _isShowDialog = false;
  @override
  void hideLoading() {
    if (mounted && _isShowDialog) {
      _isShowDialog = false;
      LoadingDialog.hide(context);
    }
  }

  @override
  void showLoading() {
    /// 避免重复弹出
    if (mounted && !_isShowDialog) {
      _isShowDialog = true;
      Future.delayed(Duration.zero, () {
        LoadingDialog.show(context);
      });
    }
  }

  @override
  void showToast(String msg) {
    Fluttertoast.showToast(msg: msg);
  }

  @override
  void dispose() {
    super.dispose();
    presenter?.disposePresenter();
  }

  @override
  void deactivate() {
    super.deactivate();
    presenter?.deactivatePresenter();
  }

  @override
  void initState() {
    super.initState();
    presenter?.initPresenter();
  }

  @override
  void setCurrentBtnName(String btnName) {
    setState(() {
      this.currentBtnName = btnName;
    });
  }

  @override
  String getCurrentBtnName() {
    return this.currentBtnName;
  }

  @override
  void setLoading(bool loading) {
    setState(() {
      this.loading = loading;
    });
  }

  @override
  bool getLoading() {
    return this.loading;
  }
}
